﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.astd.common.manager;
using com.lover.common.json;
using com.lover.common.http;

namespace com.lover.astd.common.partner.impl
{
    public class _360Login : LoginImplBase
    {
        public _360Login() : base() { }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            logging();
            string token = "";

            ///////////////////get token
            string tokenurl = String.Format("https://login.360.cn/?o=sso&m=getToken&func=QHPass.loginUtils.tokenCallback&userName={0}&rand={1}&callback=QiUserJsonP{2}",
                _username, _rand.NextDouble(), TimeMgr.TimeStamp);
            HttpResult resp = TransferMgr.doGetPure(tokenurl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            string content = resp.getContent();
            // QHPass.loginUtils.tokenCallback({"errno":0,"errmsg":"","token":"b25246c77cb1db7a"})
            content = content.Substring(content.IndexOf('(') + 1);
            content = content.Substring(0, content.IndexOf(')'));
            JsonTextParser parser = new JsonTextParser();
            JsonObjectCollection obj_token = (JsonObjectCollection)parser.Parse(content);
            IEnumerator<JsonObject> token_enumer = obj_token.GetEnumerator();
            while (token_enumer.MoveNext())
            {
                JsonStringValue token_item = token_enumer.Current as JsonStringValue;
                if (token_item == null) continue;
                if (token_item.Name != "token") continue;
                token = token_item.Value;
            }
            if (token == "") { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            token = token.ToLower();

            ////////////start login
            string loginurl = String.Format("https://login.360.cn/?o=sso&m=login&from=pcw_home&rtype=data&func=QHPass.loginUtils.loginCallback&userName={0}&pwdmethod=1&password={1}&isKeepAlive=0&token={2}&captFlag=1&captId=i360&captCode=&r={3}&callback=QiUserJsonP{3}",
                _username, _md5_password_lower, token, TimeMgr.TimeStamp);
            if (verify_code != null && verify_code != "")
            {
                loginurl = String.Format(
                    "https://login.360.cn/?o=sso&m=login&from=pcw_home&rtype=data&func=QHPass.loginUtils.loginCallback&userName={0}&pwdmethod=1&password={1}&isKeepAlive=0&token={2}&captFlag=1&captId=i360&captCode={3}&r={4}&callback=QiUserJsonP{4}",
                    _username, _md5_password_lower, token, verify_code, TimeMgr.TimeStamp);
            }
            resp = TransferMgr.doGetPure(loginurl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }
            content = resp.getContent();
            // QHPass.loginUtils.loginCallback({"errno":0,"errmsg":"","s":"...",
            //          "userinfo":{"qid":"37450459","userName":"\u968f\u7f18\u724c\u65b9\u4fbf\u9762","nickName":"\u5c0f\u732a\u4e4b\u6012","realName":"",
            //                      "imageId":"1_t01536ff7b6c6612aab","theme":"360","src":"360se","type":"formal","loginEmail":"wangzj03@gmail.com","loginTime":"1390360726","lm":"",
            //                      "unSafeLogin":"0","isKeepAlive":"0","crumb":"486ca7","imageUrl":"http:\/\/quc.qhimg.com\/dm\/48_48_80\/t01536ff7b6c6612aab.jpg"}})
            content = content.Substring(content.IndexOf('(') + 1);
            content = content.Substring(0, content.IndexOf(')'));
            JsonObjectCollection obj_login = (JsonObjectCollection)parser.Parse(content);
            IEnumerator<JsonObject> login_enumer = obj_login.GetEnumerator();
            string login_s = "", errmsg = "", captchaurl = "";
            while (login_enumer.MoveNext())
            {
                JsonStringValue login_item = login_enumer.Current as JsonStringValue;
                if(login_item == null) continue;
                if (login_item.Name == "errmsg") errmsg = login_item.Value;
                if (login_item.Name == "capturl") captchaurl = login_item.Value;
                if (login_item.Name == "s")
                {
                    login_s = login_item.Value;
                    break;
                }
            }
            if (login_s == "")
            {
                if (errmsg.IndexOf("") >= 0)
                {
                    result.StatusCode = LoginStatusCode.NeedVerifyCode;
                    result.ErrMessage = errmsg;
                    result.CaptchaUrl = captchaurl + "&r=" + TimeMgr.TimeStamp.ToString();
                    result.CaptchaImage = LoginMgr.getInstance().getCaptchaImage(result.CaptchaUrl, ref cookies);
                    result.WebCookies = cookies;
                }
                else
                {
                    result.StatusCode = LoginStatusCode.FailInLogin;
                }
                return result;
            }
            //////////1360 set login cookie
            string cookie_to_1360_url = String.Format(
                "http://login.1360.com/?o=sso&m=setcookie&func=QHPass.loginUtils.setCookieCallback&s={0}&callback=QiUserJsonP{1}",
                login_s, TimeMgr.TimeStamp);
            resp = TransferMgr.doGetPure(cookie_to_1360_url, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }
            content = resp.getContent();
            // QHPass.loginUtils.setCookieCallback({"domain":"1360.com","errno":0,"errmsg":""})
            content = content.Substring(content.IndexOf('(') + 1);
            content = content.Substring(0, content.IndexOf(')'));
            JsonObjectCollection obj_1360 = (JsonObjectCollection)parser.Parse(content);
            IEnumerator<JsonObject> _1360_enumer = obj_1360.GetEnumerator();
            bool set_1360_success = false;
            while (_1360_enumer.MoveNext())
            {
                JsonStringValue _1360_item = _1360_enumer.Current as JsonStringValue;
                if (_1360_item == null) continue;
                if (_1360_item.Name == "errmsg")
                {
                    if (_1360_item.Value == "") set_1360_success = true;
                    break;
                }
            }
            if (!set_1360_success)
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
                return result;
            }

            string redirecturl = String.Format("http://dock.wan.360.cn/game_login.php?server_id=S{0}&src=iwan-yxlist-astd&gamekey=astd", _acc.ServerId);

            processRedirect(redirecturl, result, ref cookies);
            return result;
        }
    }
}
